<template>
<div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
        <!-- 添加角色按钮区域 -->
        <el-row>
            <el-col>
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>

        <!-- 表格区域 -->
        <el-table :data="roleList" border stripe row-key="id">
            <!-- 展开列 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
                        <!-- 渲染一级权限 -->
                        <el-col :span="5">
                            <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19">
                            <!-- 通过for循环嵌套渲染二级权限 -->
                            <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{ item2.authName }}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <!-- 通过for循环嵌套渲染三级权限 -->
                                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRightById(scope.row, item3.id)">
                                        {{ item3.authName }}
                                    </el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- 编辑按钮 -->
                    <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.id)">编辑</el-button>
                    <!-- 删除按钮 -->
                    <el-button type="danger" size="mini" icon="el-icon-edit" @click="removeUserById(scope.row.id)">删除</el-button>
                    <!-- 分配权限按钮 -->
                    <el-button type="warning" icon="el-icon-edit" size="mini" @click="setRights(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加用户对话框 -->
        <el-dialog title="提示" :visible.sync="addDialogVisible" width="50%" @close="addUserClose">
            <!-- 输入信息区域 -->
            <el-form :model="addUserForm" :rules="addUserRules" ref="addUserRef" label-width="80px">
                <!-- 内容主体区域 -->
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addUserForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addUserForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部按钮区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUsers">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑按钮对话框 -->
        <el-dialog title="提示" :visible.sync="editDialogVisible" width="50%" @close="editUserClose">
            <!-- 输入信息区域 -->
            <el-form :model="editUserForm" :rules="editUserRules" ref="editUserRef" label-width="80px">
                <!-- 内容主体区域 -->
                <el-form-item label="角色名称" prop="uname">
                    <el-input v-model="editUserForm.roleName" disabled></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="describe">
                    <el-input v-model="editUserForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部按钮区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限按钮对话框 -->
        <el-dialog title="提示" :visible.sync="setRightsDialogVisible" width="50%" @close='setRightsClose'>
            <!-- 树形控件区域 -->
            <el-tree :data="setRightsList" :props="treeProps" show-checkbox node-key='id' default-expand-all :default-checked-keys='defkeys' ref='treeRef'></el-tree>

            <!-- 底部按钮区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </el-card>
</div>
</template>

<script>
export default {
    data() {
        return {
            roleList: [],
            // 用来控制添加用户按钮的显示与隐藏
            addDialogVisible: false,
            // 用来保存用户的信息对象
            addUserForm: {
                roleName: '',
                roleDesc: ''
            },
            // 添加用户表单的验证规则
            addUserRules: {
                roleName: [{
                        required: true,
                        message: '请输入用户名称',
                        trigger: 'blur'
                    },
                    {
                        min: 3,
                        max: 6,
                        message: '长度在 3 到 6 个字符',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [{
                        required: true,
                        message: '请输入用户描述',
                        trigger: 'blur'
                    },
                    {
                        min: 3,
                        max: 6,
                        message: '长度在 3 到 6 个字符',
                        trigger: 'blur'
                    }
                ]
            },
            // 用来控制编辑按钮的显示与隐藏
            editDialogVisible: false,
            // 用来保存查询到的用户的信息对象
            editUserForm: {},
            editUserRules: {
                roleName: [{
                        required: true,
                        message: '请输入角色名称',
                        trigger: 'blur'
                    },
                    {
                        min: 3,
                        max: 6,
                        message: '长度在 3 到 6 个字符',
                        trigger: 'blur'
                    }
                ],
                roleDesc: [{
                        required: true,
                        message: '请输入角色描述',
                        trigger: 'blur'
                    },
                    {
                        min: 3,
                        max: 6,
                        message: '长度在 3 到 6 个字符',
                        trigger: 'blur'
                    }
                ]
            },
            // 用来控制分配权限对话框的显示与隐藏
            setRightsDialogVisible: false,
            // 用来保存权限数据
            setRightsList: [],
            // 树形控件的属性绑定对象
            treeProps: {
                children: 'children',
                label: 'authName'
            },
            // 默认选中的节点id数组
            defkeys: [],
            // 当前即将分配权限的角色id
            roleId: ''
        }
    },
    created() {
        this.getRoleList()
    },
    methods: {
        // 获取角色所有列表
        async getRoleList() {
            const {
                data: res
            } = await this.$http.get('roles')

            if (res.meta.status !== 200) {
                return this.$message.error('获取角色列表失败！')
            }

            this.roleList = res.data
            //   console.log(this.roleList)
        },
        // 点击按钮添加用户
        addUsers() {
            this.$refs.addUserRef.validate(async (valid) => {
                // console.log(valid)
                // 校验失败直接返回
                if (!valid) return false
                // 可以发起添加用户的网络请求
                const {
                    data: res
                } = await this.$http.post('roles', this.addUserForm)
                if (res.meta.status !== 201) {
                    this.$message.error('创建角色失败！')
                }
                this.$message.success('创建角色成功！')
                // 关闭添加用户对话框
                this.addDialogVisible = false
                // 重新获取用户列表数据
                this.getRoleList()
            })
            console.log(this.addUserForm)
        },
        // 监听添加用户对话框关闭事件
        addUserClose() {
            this.$refs.addUserRef.resetFields()
        },
        // 监听编辑对话框关闭事件
        editUserClose() {
            this.$refs.editUserRef.resetFields()
        },
        // 点击修改按钮，弹出修改对话框
        async showEditDialog(id) {
            const {
                data: res
            } = await this.$http.get('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('修改用户信息失败！')
            }
            this.editUserForm = res.data
            // console.log(this.editFrom)
            this.editDialogVisible = true
        },
        // 修改用户信息并提交
        editUserInfo() {
            this.$refs.editUserRef.validate(async (valid) => {
                if (!valid) return false

                // 发起修改用户的提交请求
                const {
                    data: res
                } = await this.$http.put(
                    'roles/' + this.editUserForm.roleId, {
                        roleName: this.editUserForm.roleName,
                        roleDesc: this.editUserForm.roleDesc
                    }
                )
                if (res.meta.status !== 200) {
                    return this.$message.error('更新用户信息失败！')
                }
                this.$message.success('更新用户信息成功！')
                // 关闭对话框
                this.editDialogVisible = false
                // 重新渲染用户列表数据
                this.getRoleList()
            })
        },
        // 点击删除按钮删除当前用户
        async removeUserById(id) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该用户, 是否继续?',
                '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch((err) => err)
            // 如果用户确认了删除，则返回字符串confirm
            // 如果用户取消了删除，则返回字符串cancel
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            // console.log('确认了删除')
            const {
                data: res
            } = await this.$http.delete('roles/' + id)
            if (res.meta.status !== 200) {
                return this.$message.error('删除用户失败')
            }
            this.$message.success('删除用户成功')
            this.getRoleList()
        },
        // 点击删除按钮删除三级权限
        async removeRightById(role, id) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除该用户, 是否继续?',
                '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch((err) => err)
            // 如果用户确认了删除，则返回字符串confirm
            // 如果用户取消了删除，则返回字符串cancel
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            // console.log('确认了删除')
            const {
                data: res
            } = await this.$http.delete(
                `roles/${role.id}/rights/${id}`
            )
            if (res.meta.status !== 200) {
                return this.$message.error('删除用户失败')
            }
            // this.getRoleList()
            role.children = res.data
        },
        // 点击分配权限按钮获取权限数据
        async setRights(role) {
            this.roleId = role.id
            const {
                data: res
            } = await this.$http.get('rights/tree')
            if (res.meta.status !== 200) {
                return this.$message.error('获取用户权限列表失败')
            }
            this.setRightsList = res.data
            // 递归获取三级权限的id
            this.getLeafKeys(role, this.defkeys)

            this.setRightsDialogVisible = true
            // console.log(this.setRightsList)
        },
        // 通过递归的形式，获取角色下所有的三级权限的id，并保存到defkeys数组中
        getLeafKeys(node, arr) {
            // 如果当前node节点不包含children属性，则是三级节点
            if (!node.children) {
                return arr.push(node.id)
            }

            node.children.forEach(item => {
                this.getLeafKeys(item, arr)
            })
        },
        // 监听分配权限对话框的关闭事件
        setRightsClose() {
            this.defkeys = []
        },
        async allotRights() {
            const keys = [
                this.$refs.treeRef.getCheckedKeys(),
                this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const {
                data: res
            } = await this.$http.post(`roles/${this.roleId}/rights`, {
                rids: idStr
            })

            if (res.meta.status !== 200) {
                return this.$message.error('分配角色权限失败！')
            }
            this.$message.success('分配角色权限成功！')

            this.getRoleList()
            this.setRightsDialogVisible = false
        }
    }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}

.vcenter {
    display: flex;
    align-items: center;
}
</style>
